<template>
  <div class="borrow-orders">
    <!-- 搜索过滤区 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="借阅证号">
          <el-input v-model="searchForm.cardno" placeholder="请输入借阅证号">
            <template #append>
              <el-button :icon="Camera" @click="openScan('reader')" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="图书条码">
          <el-input v-model="searchForm.isbn" placeholder="请输入图书条码">
            <template #append>
              <el-button :icon="Camera" @click="openScan('book')" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="借阅状态">
          <el-select v-model="searchForm.borrow_status" placeholder="请选择状态" style="width: 120px">
            <el-option label="已借出" value="0" />
            <el-option label="已归还" value="1" />
            <el-option label="逾期" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-container">
      <el-table 
        :data="orderList" 
        v-loading="loading"
        stripe 
        style="width: 100%"
        :border="true"
        table-layout="fixed"
      >
        <el-table-column 
          prop="order_id" 
          label="订单编号" 
          width="100" 
          align="center"
          header-align="center"
        />
        <el-table-column 
          prop="cardno" 
          label="借阅证号" 
          width="120" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="real_name" 
          label="读者姓名" 
          width="100" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="isbn" 
          label="图书条码" 
          width="140" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="title" 
          label="图书名称" 
          min-width="200" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="borrow_time" 
          label="借阅时间" 
          width="160" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="due_time" 
          label="应还时间" 
          width="160" 
          align="center" 
          header-align="center" 
        />
        <el-table-column 
          prop="borrow_status" 
          label="状态" 
          width="80" 
          align="center" 
          header-align="center"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.borrow_status)">
              {{ getStatusText(scope.row.borrow_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="120" 
          align="center" 
          header-align="center"
        >
          <template #default="scope">
            <el-button link type="primary" @click="showDetail(scope.row)">
              查看详情
            </el-button>
            <el-button 
              v-if="scope.row.borrow_status === '0'"
              link 
              type="success" 
              @click="handleReturn(scope.row)"
            >
              确认归还
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          prev-text="上一页"
          next-text="下一页"
          total-text="共"
          size-change-text="条/页"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      title="借阅详情" 
      width="500px"
    >
      <div class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单编号">
            {{ currentOrder.order_id }}
          </el-descriptions-item>
          <el-descriptions-item label="读者信息">
            {{ currentOrder.real_name }}（{{ currentOrder.cardno }}）
          </el-descriptions-item>
          <el-descriptions-item label="图书信息">
            {{ currentOrder.title }}（{{ currentOrder.isbn }}）
          </el-descriptions-item>
          <el-descriptions-item label="借阅时间">
            {{ currentOrder.borrow_time }}
          </el-descriptions-item>
          <el-descriptions-item label="应还时间">
            {{ currentOrder.due_time }}
          </el-descriptions-item>
          <el-descriptions-item label="实际归还时间" v-if="currentOrder.return_time">
            {{ currentOrder.return_time }}
          </el-descriptions-item>
          <el-descriptions-item label="借阅状态">
            {{ getStatusText(currentOrder.borrow_status) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 扫码组件 -->
    <el-dialog v-model="scanVisible" title="扫描二维码/条码" width="500px">
      <SteamBarcodeReader @decode="handleScanResult" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Camera } from '@element-plus/icons-vue';
//扫描二维码和条形码组件
import SteamBarcodeReader from "@/components/steambarcodereader.vue";
//引入统一请求接口
import { getBorrowOrderPagerData } from '@/api/index';

// 搜索表单
const searchForm = reactive({
  cardno: '',
  isbn: '',
  borrow_status: ''
});

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 订单列表数据
const orderList = ref([]);

// 详情对话框
const detailVisible = ref(false);
const currentOrder = ref({});

// 状态处理函数
const getStatusType = (status) => {
  const types = {
    '0': 'warning',  // 借出
    '1': 'success',  // 已还
    '2': 'danger'    // 逾期
  };
  return types[status] || 'info';
};

const getStatusText = (status) => {
  const texts = {
    '0': '已借出',
    '1': '已归还',
    '2': '已逾期'
  };
  return texts[status] || '未知';
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 确保分页参数为数字类型
    const params = {
      currentPage: Number(currentPage.value),
      pageSize: Number(pageSize.value)
    };
    
    // 只有在有值的情况下才添加搜索条件
    if (searchForm.cardno) params.cardno = searchForm.cardno;
    if (searchForm.isbn) params.isbn = searchForm.isbn;
    if (searchForm.borrow_status) params.borrow_status = searchForm.borrow_status;

    const res = await getBorrowOrderPagerData(params);
    if (res?.code === 200) {
      orderList.value = res.data.data || [];
      total.value = parseInt(res.data.total) || 0;
    } else {
      orderList.value = [];
      total.value = 0;
      ElMessage.error(res?.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('加载数据错误:', error);
    orderList.value = [];
    total.value = 0;
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => searchForm[key] = '');
  currentPage.value = 1;
  loadData();
};

const showDetail = (row) => {
  currentOrder.value = row;
  detailVisible.value = true;
};

const handleReturn = (row) => {
  ElMessage.success('图书归还成功！');
  // 实现归还逻辑
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadData();
};

// 扫码相关
const scanVisible = ref(false);
const scanType = ref('');  // 'reader' 或 'book'

const openScan = (type) => {
  scanType.value = type;
  scanVisible.value = true;
};

//扫码方法
const handleScanResult = async (result) => {
  // 首先判断扫描结果是否有效
  if (!result) {
    ElMessage.error('扫描失败，请重试');
    return;
  }

  try {
    // 获取扫描文本
    const scannedText = result.text || result;
    
    // 根据扫描类型更新对应的输入框
    if (scanType.value === 'reader') {
      searchForm.cardno = scannedText;
    } else {
      searchForm.isbn = scannedText;
    }

    // 关闭扫描窗口
    scanVisible.value = false;
    
    // 播放提示音
    const audio = new Audio('/assets/beep.mp3');
    audio.play().catch(err => console.warn('播放提示音失败:', err));

    ElMessage.success('扫描成功');
    
    // 自动触发搜索
    handleSearch();
  } catch (error) {
    console.error('扫描处理错误:', error);
    ElMessage.error('扫描处理出错，请重试');
  }
};

// 初始化加载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.borrow-orders {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

:deep(.el-table) {
  width: 100%;
  margin-top: 20px;
}

:deep(.el-table--border) {
  border: 1px solid #EBEEF5;
}

:deep(.el-table__header) th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  text-align: center !important;
}

:deep(.el-table__row) td {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  white-space: normal;
  padding: 0;
  text-align: center;
}

:deep(.el-table .cell .el-button) {
  padding: 4px 8px;
  margin: 0 4px;
}

:deep(.el-table .cell .el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #EBEEF5;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  padding: 20px;
}

:deep(.el-input) {
  width: 220px;  /* 调整输入框宽度为220px */
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append .el-button) {
  padding: 8px 12px;  /* 调整按钮内边距 */
  margin: 0;
  height: 100%;      /* 确保按钮高度与输入框一致 */
  border: none;      /* 移除按钮边框 */
}

:deep(.el-input-group__append .el-button:hover) {
  background-color: var(--el-button-hover-bg-color);
  color: var(--el-button-hover-text-color);
}
</style>
